var prefs = new gadgets.Prefs();
var myService = null;
   
function setupMyService() {
	myService = new google.gdata.calendar.CalendarService('listaProfesionales');
	myService.useOAuth('google');
}

function initGadget(){
	google.load('gdata', '2.0');
	google.setOnLoadCallback(setupMyService);
	//gadgets.window.adjustHeight();
	cargarProfesionales();
}

function cargarProfesionales(){
	gadgets.window.adjustHeight();
	google.calendar.getPreferences(	function(prefs){
										user = "";
										if ('viewer' in prefs) {
											user = prefs.viewer;
										}
										var params = {};
										params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
										var url = "http://calendardemosam.appspot.com/obtenerAnalistas.action?idAdmisor=" + user;
										gadgets.io.makeRequest(noCacheURL(url), response, params);		
									});
}


function response(obj) { 
	var jsondata = obj.data;
	var html = "";
	for (var key in jsondata) {
		var profesional = jsondata[key];
		html += "<a class='linkProfesional' href='javascript:seleccionarCalendario(\"" + 
				profesional.nombre + 
				"\", \"" + 
				profesional.apellido + 
				"\")' id='profesional" + key + "'>";
		html += profesional.nombre + " " + profesional.apellido;
		html += "</a>";
	}
	document.getElementById('content_div').innerHTML = html;
	gadgets.window.adjustHeight();
}

function noCacheURL(url){
	refreshInterval = 1;
	var ts = new Date().getTime();
	var sep = "?";
	if (refreshInterval && refreshInterval > 0) {
		ts = Math.floor(ts / (refreshInterval * 1000));
	}
	if (url.indexOf("?") > -1) {
		sep = "&";
	}
	return [ url, sep, "nocache=", ts ].join("");
}

function seleccionarCalendario(nombre, apellido) {            
	var callback = function(response) {
		var html = "";
		if (response.oauthApprovalUrl) {
			window.open(response.oauthApprovalUrl,'Autorizar'); 
		} else if (response.feed) {

 			var cd = document.getElementById("content_div");
			cd.style.display = "none";
			var loading = document.getElementById("loading");
			loading.style.display = "block";
			gadgets.window.adjustHeight();

			var entries = response.feed.entry;
			var count = entries.length;
			var existe = false;
			for (var i = 0; i < entries.length; i++) {
				var calendarEntry = entries[i];
				var calendarTitle = calendarEntry.getTitle().getText();
				if(calendarTitle == (nombre + " " + apellido)){
					calendarEntry.getSelected().setValue(true);
					existe = true;
				}else{
					calendarEntry.getSelected().setValue(false);
				}
				calendarEntry.updateEntry(	function(entryRoot){
												count = count - 1;
												if(count ==  0 && existe){
													window.open("https://www.google.com/calendar/render?tab=cc", "_top");
												}
											}
											, error);
			}
			
			if(!existe){
				var feedUri = 'https://www.google.com/calendar/feeds/default/owncalendars/full';
				var entry = new google.gdata.calendar.CalendarEntry();
				entry.setTitle(google.gdata.atom.Text.create(nombre + " " + apellido));
				var hidden = new google.gdata.calendar.HiddenProperty();
				hidden.setValue(false);
				entry.setHidden(hidden);
				
				
				var timeZone = new google.gdata.calendar.TimeZoneProperty();
				timeZone.setValue("America/Argentina/Buenos_Aires");
				entry.setTimeZone(timeZone);
				var callback = function(result) {
								alert("El calendario para " + nombre + " " + apellido + " no existía.\nAcaba de ser creado");
								window.open("https://www.google.com/calendar/render?tab=cc", "_top");
								};
				var handleError = function(error) {alert(error);};
				myService.insertEntry(feedUri, entry, callback, handleError, google.gdata.calendar.CalendarEntry);
			}
			
		} else {
			html = 'OAuth error: ' + response.oauthError + ': ' + response.oauthErrorText;
		}
		if(html == ""){
			
		}else{
			document.getElementById('content_div').innerHTML = html;
		}
						
	};
	myService.getOwnCalendarsFeed('https://www.google.com/calendar/feeds/default/owncalendars/full', callback, callback);
}

function error(error) {
	alert(error);
}

gadgets.util.registerOnLoadHandler(initGadget);
